import React from 'react';
import PropTypes from 'prop-types';
import cn from 'classnames';
import Helper from '../../components/Helper';
import Checkbox from './Checkbox';
import s from './CheckboxGroup.module.css';
// value:['1','2']
function CheckboxGroup({
	className,
	single,
	checked: checkedProps = {},
	options,
	onChange,
	checkboxClassName,
	tipIconClassName,
	boxClassName,
	tipProps,
	value,
	...props
}) {
	options.map(item => {
		if (value.includes(item.value)) {
			checkedProps[item.value] = true;
		} else {
			checkedProps[item.value] = false;
		}
	});
	const propState = single ? { [checkedProps]: true } : checkedProps;
	const [checkedState, setChecked] = React.useState(propState);
	const checked = propState || checkedState;
	const handleCheck = nextChecked => {
		if (!checkedProps) {
			setChecked(nextChecked);
		}
		const arr = [];
		Object.keys(nextChecked).map(e => {
			nextChecked[e] && arr.push(e);
		});
		single ? onChange(Object.keys(nextChecked)[0]) : onChange(arr);
	};

	return (
		<span className={cn(className, s.checkboxGroup)}>
			{options.map(({ value, label, ...prop }) => (
				<span key={value} className={cn(s.checkboxContainer, boxClassName)}>
					<Checkbox
						{...props}
						key={value}
						className={cn(s.checkbox, checkboxClassName)}
						type={single ? 'radio' : 'checkbox'}
						checked={checked[value]}
						onChange={e =>
							single
								? handleCheck(
										e.target.checked
											? {
													[value]: e.target.checked,
											  }
											: {}
								  )
								: handleCheck({
										...checked,
										[value]: e?.target?.checked,
								  })
						}
					>
						{label}
					</Checkbox>
					{prop?.tip && (
						<Helper
							overlayClassName={s.helpTooltip}
							overlay={prop?.tip}
							placement="top"
							{...(prop?.tipProps || {})}
						/>
					)}
				</span>
			))}
		</span>
	);
}

CheckboxGroup.propTypes = {
	value: PropTypes.any,
	className: PropTypes.string,
	single: PropTypes.bool,
	checked: PropTypes.oneOfType([PropTypes.string, PropTypes.object]),
	options: PropTypes.arrayOf(
		PropTypes.shape({
			label: PropTypes.string.isRequired,
			value: PropTypes.any.isRequired,
			tip: PropTypes.node,
		})
	).isRequired,
	onChange: PropTypes.func.isRequired,
	checkboxClassName: PropTypes.string,
	tipIconClassName: PropTypes.string,
	boxClassName: PropTypes.string,
	tipProps: PropTypes.object,
};
CheckboxGroup.defaultProps = {
	className: s.CheckboxGroup,
	// 是否单选
	single: false,
	borderless: false,
	onChange: () => {},
	tipProps: {},
};

export default CheckboxGroup;
export { Checkbox };
